<template>
  <el-drawer v-model="dialogVisible" title="数据更新">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm2"
    >
      <el-alert
        title="数据更新存在一定滞后性，我们推荐在查看某段时期的数据前先对该时期数据进行更新"
        type="success"
        :closable="false"
      />
      <br />
      <el-form-item label="日期：" prop="date">
        <el-date-picker
          v-model="ruleForm.date"
          type="monthrange"
          range-separator="至"
          start-placeholder="起始时间"
          end-placeholder="结束时间"
          format="YYYY-MM"
          value-format="YYYY-MM"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit(ruleFormRef)">确定</el-button>
      </span>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { postSiteDetailCalculate } from '@/api/controller/site-detail-controller/index'
  import { ElMessage } from 'element-plus'
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = ref<any>({
    date: null,
  })

  const rules = reactive({
    date: [{ required: true, message: '请选择日期', trigger: 'blur' }],
  })
  const dialogVisible = ref(false)
  //新增或修改
  const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        let a = {
          startYear: ruleForm.value.date[0].split('-')[0] * 1,
          startMonth: ruleForm.value.date[0].split('-')[1] * 1,
          endYear: ruleForm.value.date[1].split('-')[0] * 1,
          endMonth: ruleForm.value.date[1].split('-')[1] * 1,
        }
        const result = await postSiteDetailCalculate(a, { loading: true })
        if (result.code === 200) {
          dialogVisible.value = false
          await emit('getData')
          ElMessage.success('更新成功')
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }
  const show = () => {
    ruleForm.value.date = null
    dialogVisible.value = true
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }

  const emit = defineEmits(['getData'])
  defineExpose({
    show,
  })
</script>
